package com.ren.filter;

import com.ren.entity.User;
import com.ren.service.UserService;
import com.ren.service.UserServiceImpl;
import com.ren.util.CookieUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * Created by Zero on 2017/4/7.
 */
public class AutoLoginUser implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;

        if (request.getSession().getAttribute("USER") == null){

            Cookie cookie1 = CookieUtils.findCookie(request.getCookies(),
                    "USERACCOUNT");
            Cookie cookie2 = CookieUtils.findCookie(request.getCookies(),
                    "USERPWD");

            if (cookie1 != null && cookie2 != null){

                String userName = URLDecoder.decode(cookie1.getValue(), "utf-8");
                String userPassword = URLDecoder.decode(cookie2.getValue(),"utf-8");

                User user = null;
                UserService userService = new UserServiceImpl();

                try {
                    user = userService.findByUserNameAndPwd(userName,userPassword);
                }catch (NullPointerException e){
                    e.printStackTrace();
                }

                if (user != null){
                    HttpSession session = request.getSession();
                    session.setAttribute("USER",user);
                }
            }

        }

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }
}
